#pragma once

#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>

class InetAddr
{
private:
    void NetToHost()
    {
        _port = ntohs(_addr.sin_port);
        _ip = inet_ntoa(_addr.sin_addr);
    }

    void HostToNet()
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = inet_addr(_ip.c_str());
    }

public:
    InetAddr(const struct sockaddr_in addr)
        :_addr(addr)
    {
        NetToHost();
    }

    InetAddr(uint16_t port, std::string ip = "0.0.0.0")
        :_port(port)
        ,_ip(ip)
    {
        HostToNet();
    }

    std::string Ip()
    {
        return _ip;
    }

    uint16_t Port()
    {
        return _port;
    }

    struct sockaddr* Addr()
    {
        return (struct sockaddr*)&_addr;
    }

    socklen_t Len()
    {
        return sizeof(_addr);
    }

    std::string ToString()
    {
        return _ip + "-" + std::to_string(_port);
    }

    bool operator==(const InetAddr& addr)
    {
        return (_ip == addr._ip && _port == addr._port);
    }

private:    
    uint16_t _port;
    struct sockaddr_in _addr;
    std::string _ip;
};